import _ from 'underscore';
import TaskLineCollection from './TaskLineCollection.js';
import BaseModel from "../../base/models/BaseModel.js";
import Radio from "backbone.radio";


const TaskGroupModel = BaseModel.extend({
    props: [
        'id',
        'order',
        'title',
        'description',
        'lines',
        'task_id',
        'display_details',
        'total_ht',
        'total_ttc'
    ],
    defaults() {
        return {
            'display_details': true
        };
    },
    validation: {
        lines: function (value) {
            if (value.length === 0) {
                return `Chapitre « ${this.get('title')} » : Veuillez saisir au moins un produit`;
            }
            /* Doing line validation here, because cannot find a way to
             * call TaskLineModel.validate() cleanly :/.
             */
            let dateRequired = Radio.channel('config').request('has:form_section', 'composition:classic:lines:date');

            if (dateRequired) {
                for (let i = 0; i < value.length; i++) {
                    if (value[i].date == null) {
                        return "Tous les produits doivent mentionner une date d'exécution";
                    }
                }
            }
        }
    },
    initialize: function () {
        this.populate();
        this.on('change:id', () => this.populate());

        this.listenTo(this.lines, 'saved', this.updateLines);
        this.listenTo(this.lines, 'destroyed', this.updateLines);
        this.listenTo(this.lines, 'synced', this.updateLines);
    },
    populate: function () {
        if (this.get('id')) {
            this.lines = new TaskLineCollection(this.get('lines'));
            this.lines.url = this.url() + '/task_lines';
        }
    },
    updateLines() {
        this.set('lines', this.lines.toJSON());
    },
    ht: function () {
        return this.get('total_ht');
    },
    tvaParts: function () {
        return this.lines.tvaParts();
    },
    ttc: function () {
        return this.get('total_ttc');
    }
});
export default TaskGroupModel;